﻿using BRbacSystem.Repositorys;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Microsoft.IdentityModel.Tokens;
using DefenseQuestion.WebAPI.Filters;
using DefenseQuestion.Application.UserApplication;
using DefenseQuestion.Application.UserApplication.Dto;
using DefenseQuestion.Application;
using DefenseQuestion;
using System.Collections.Generic;

namespace BRbacSystem.WebAPI.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[CustomerAuthorizationFilter]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IWebHostEnvironment env;
        /// <summary>
        /// UserController注入
        /// </summary>
        /// <param name="userService"></param>
        /// <param name="env"></param>
        public UserController(IUserService userService, IWebHostEnvironment env)
        {
            _userService = userService;
            this.env = env;
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="Model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddUser(AddUserDto Model)
        {
            var list = await _userService.AddUserAsync(Model);
            return Ok(list);
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateUser(AddUserDto user)
        {
            var list = await _userService.UpdateUserAsync(user);
            return Ok(list);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleteUser(int id)
        {
            var list = await _userService.DeleteUserAsync(id);
            return Ok(list);
        }
        /// <summary>
        /// 显示用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUsers(string UserName, int pageIndex, int pageSize)
        {
            var list = _userService.GetUsersAsync(UserName, pageIndex, pageSize);
            var code = list.Code;
            return Ok(new { list, code });
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> LoginAsync(LoginDto dto)
        {
            var list = await _userService.LoginAsync(dto);
            return Ok(list);
        }
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> Upload(IFormFile file)
        {
            //var dir = $"/UploadFiles/Images/{DateTime.Now.ToString("yyyy")}/{DateTime.Now.ToString("MMdd")}/";
            var code = Result.Success;
            var dir = $"/UploadFiles/Images/";
            if (!Directory.Exists($"{env.WebRootPath}{dir}"))
            {
                Directory.CreateDirectory($"{env.WebRootPath}{dir}");
            }
            Random random = new Random();
            var fileName = $"{dir}{DateTime.Now.ToString("yyyyMMddHHmmss")}-{random.Next(100, 999)}{Path.GetExtension(file.FileName)}";
            using (FileStream fileStream = new FileStream($"{env.WebRootPath}{fileName}", FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            return Ok(new
            {
                code,
                fileName
            });
        }
        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult FindUser(int Id)
        {
            var list = _userService.FindUser(Id);
            return Ok(list);
        }
        /// <summary>
        /// Token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCurrentUser([FromQuery(Name = "token")] string token)
        {
            ////验证解析Jwt令牌
            //var isvalid = JwtSecurityTokenHandler.(token, out var claims);
            var userId = HttpContext.User.Claims.FirstOrDefault(claim => claim.Type == "sub")?.Value;
            var userName = HttpContext.User.Claims.FirstOrDefault(claim => claim.Type == "username")?.Value;
            return Ok(new { userId = userId, userName = userName });
        }
        /// <summary>
        /// 获取用户类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserType()
        {
            var list = _userService.GetUserType();
            return Ok(list);
        }
    }
}
